<template>
  <div class="product-management">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>库存管理</span>
          <div>
            <el-button type="primary" @click="handleAdd">新增产品</el-button>
            <el-button :icon="Refresh" @click="loadProducts" />
          </div>
        </div>
      </template>

      <!-- 搜索栏 -->
      <div class="search-bar">
        <el-input
          v-model="searchParams.name"
          placeholder="产品名称"
          style="width: 200px"
          clearable
        />
        <el-select
          v-model="searchParams.category"
          placeholder="产品分类"
          clearable
          style="width: 150px; margin-left: 10px"
        >
          <el-option
            v-for="item in categories"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-button type="primary" style="margin-left: 10px" @click="handleSearch">
          搜索
        </el-button>
      </div>

      <!-- 数据表格 -->
      <el-table :data="filteredProducts" border stripe height="500">
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="产品名称" min-width="150" />
        <el-table-column prop="category" label="分类" width="120">
          <template #default="{ row }">
            <el-tag :type="categoryTagType(row.category)">
              {{ row.category }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="price" label="价格" width="120" align="right">
          <template #default="{ row }">¥{{ row.price.toFixed(2) }}</template>
        </el-table-column>
        <el-table-column prop="stock" label="库存" width="100" align="center" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleEdit(row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="filteredProducts.length"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <product-form-dialog
      v-model="dialogVisible"
      :current-product="currentProduct"
      :mode="dialogMode"
      @submit="handleSubmit"
    />
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Refresh } from '@element-plus/icons-vue'
import ProductFormDialog from '@/components/ProductFormDialog.vue'

// 模拟数据
const generateProductData = () => {
  const categories = ['电子产品', '办公用品', '日用品', '食品饮料']
  const products = []
  for (let i = 1; i <= 50; i++) {
    products.push({
      id: i,
      name: `产品 ${i}`,
      category: categories[i % 4],
      price: Math.random() * 1000 + 100,
      stock: Math.floor(Math.random() * 100),
      status: 1,
      createTime: new Date()
    })
  }
  localStorage.setItem('mock-products', JSON.stringify(products))
  return products
}

// 初始化数据
let mockProducts = JSON.parse(localStorage.getItem('mock-products')) || generateProductData()

// 响应式数据
const products = ref([...mockProducts])
const searchParams = ref({
  name: '',
  category: ''
})
const currentPage = ref(1)
const pageSize = ref(10)
const dialogVisible = ref(false)
const currentProduct = ref(null)
const dialogMode = ref('add')

// 分类选项
const categories = [
  { value: '电子产品', label: '电子产品' },
  { value: '办公用品', label: '办公用品' },
  { value: '日用品', label: '日用品' },
  { value: '食品饮料', label: '食品饮料' }
]

// 计算属性
const filteredProducts = computed(() => {
  return products.value.filter(item => {
    const nameMatch = item.name.includes(searchParams.value.name)
    const categoryMatch = searchParams.value.category ? 
      item.category === searchParams.value.category : true
    return nameMatch && categoryMatch
  })
})

const categoryTagType = (category) => {
  const types = {
    '电子产品': 'primary',
    '办公用品': 'success',
    '日用品': 'warning',
    '食品饮料': 'danger'
  }
  return types[category] || 'info'
}

// 方法
const loadProducts = () => {
  // 模拟API请求
  setTimeout(() => {
    products.value = JSON.parse(localStorage.getItem('mock-products')) || []
    ElMessage.success('数据已刷新')
  }, 500)
}

const handleSearch = () => {
  currentPage.value = 1
}

const handleAdd = () => {
  currentProduct.value = null
  dialogMode.value = 'add'
  dialogVisible.value = true
}

const handleEdit = (row) => {
  currentProduct.value = { ...row }
  dialogMode.value = 'edit'
  dialogVisible.value = true
}

const handleSubmit = (formData) => {
  if (dialogMode.value === 'add') {
    formData.id = products.value.length + 1
    products.value.unshift(formData)
  } else {
    const index = products.value.findIndex(p => p.id === formData.id)
    if (index !== -1) {
      products.value.splice(index, 1, formData)
    }
  }
  localStorage.setItem('mock-products', JSON.stringify(products.value))
  ElMessage.success('操作成功')
  dialogVisible.value = false
}

const handleDelete = (id) => {
  ElMessageBox.confirm('确定删除该产品？', '警告', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    products.value = products.value.filter(p => p.id !== id)
    localStorage.setItem('mock-products', JSON.stringify(products.value))
    ElMessage.success('删除成功')
  })
}

const handleStatusChange = (row) => {
  const index = products.value.findIndex(p => p.id === row.id)
  if (index !== -1) {
    products.value.splice(index, 1, row)
    localStorage.setItem('mock-products', JSON.stringify(products.value))
    ElMessage.success('状态已更新')
  }
}

onMounted(loadProducts)
</script>

<style scoped>
.product-management {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.el-table {
  margin-top: 20px;
}
</style> 